//
//  Ugc_Detail_TBV_WX.m
//  ZITHER
//
//  Created by weixin on 2018/9/11.
//  Copyright © 2018年 weixn. All rights reserved.
//

#import "Ugc_Detail_TBV_WX.h"
#import "UgcDetailCummentCell.h"
#import "ReportView.h"
#import "UgcDetailCummentNoMoreDataCell.h"
#import "DetailFriedHeadView.h"
#import "UgcDetailCummentCell_TokenCell.h"
#import "UgcDetailCummentHeadCell_TokenCell.h"
@interface Ugc_Detail_TBV_WX()

@property (nonatomic,strong)DetailFriedHeadView * headView;

@end

@implementation Ugc_Detail_TBV_WX

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self defaultConfiguration];
        self.backgroundColor = [UIColor colorWithHex:@"f5f5f5"];
    }
    return self;
}

-(void)setUgcId:(NSString *)ugcId{
    _ugcId = ugcId;
    [self setLoad];
}

-(void)setLoad{
    @weakify(self);
    [[serviceDefualt loadGetuserCommentList:self.ugcId relType:@"1" page:self.page reponseObjctClass:[UgcCommentListModel class]]subscribeNext:^(ResponseData * x) {
        @strongify(self);
        if (x.success) {
//            [Tools showTips:x.responseRawData[@"data"][@""]];

            /**
             1.当用户第一次进来
             */        
            self.mj_footer.hidden = NO;
            UgcCommentListModel* listModel = x.responseData;
            if (listModel.list.count == 0) {
                [self.mj_footer endRefreshing];
                if (!self.type) {
                    self.type = YES;
                    self.mj_footer.hidden = YES;
                    [self.mj_footer endRefreshingWithNoMoreData];
                    return ;
                }else{
                    if (listModel.list.count == 0) {
                        if (self.page == 0) {
                            [Tools showTips:@"暂无更多数据"];
                            [self.mj_header endRefreshing];
                            [self.mj_footer endRefreshing];
                            self.mj_footer.hidden = YES;
                        }else{
                            [self.mj_footer endRefreshingWithNoMoreData];
                        }
                        return ;
                    }
                }
                if (self.page == 0) {
                    self.arrMComment = [[NSMutableArray alloc]init];
                    [Tools showTips:@"暂无评论"];
                    [self.mj_header endRefreshing];
                    [self reloadData];
                    self.mj_footer.hidden = YES;

                }else{
                    self.mj_footer.hidden = NO;
                    [Tools showTips:@"没有更多的评论"];
                    [self.mj_header endRefreshing];
                    [self reloadData];
                    return ;
                }
            }else{
                if (self.page == 0) {
                    self.arrMComment = [[NSMutableArray alloc]init];
                    for (UgcCommentListModelSub *model in listModel.list) {
                        [self.arrMComment addObject:model];
                        if (model.sonCommentList.count!=0) {
                            for (UgcCommentListModelSub *model1 in model.sonCommentList) {
                                [self.arrMComment addObject:model1];
                            }
                        }
                    }
                }else{
                    for (UgcCommentListModelSub *model in listModel.list) {
                        [self.arrMComment addObject:model];
                        if (model.sonCommentList.count!=0) {
                            for (UgcCommentListModelSub *model1 in model.sonCommentList) {
                                [self.arrMComment addObject:model1];
                            }
                        }
                    }
                }
            }
            [self.mj_header endRefreshing];
            [self.mj_footer endRefreshing];
            [self reloadData];
            self.type = YES;
        }else{
             [Tools showTips:x.errorInfo];
            [self.mj_header endRefreshing];
            [self.mj_footer endRefreshing];
        }
    }];
}

-(void)defaultConfiguration{


    
    self.delegate = self;
    self.dataSource = self;
    self.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.rowHeight = UITableViewAutomaticDimension;
    self.estimatedRowHeight = 1000;
    self.showsHorizontalScrollIndicator = NO;
    self.showsVerticalScrollIndicator = NO;
    
    self.tableFooterView = [UIView new];
    self.estimatedSectionHeaderHeight = 0.f;
    self.sectionHeaderHeight = UITableViewAutomaticDimension;
    // 希望footer高为0
    self.estimatedSectionFooterHeight = 0.f;
    self.sectionFooterHeight = 0.f;

    [self registerNib:[UINib nibWithNibName:@"UgcDetailCummentHeadCell" bundle:nil] forCellReuseIdentifier:@"UgcDetailCummentHeadCell"];
    [self registerNib:[UINib nibWithNibName:@"UgcDetailCummentCell" bundle:nil] forCellReuseIdentifier:@"UgcDetailCummentCell"];
    [self registerNib:[UINib nibWithNibName:@"UgcDetailCummentHeadCell_TokenCell" bundle:nil] forCellReuseIdentifier:@"UgcDetailCummentHeadCell_TokenCell"];
    [self registerNib:[UINib nibWithNibName:@"UgcDetailCummentCell_TokenCell" bundle:nil] forCellReuseIdentifier:@"UgcDetailCummentCell_TokenCell"];

    @weakify(self);
    self.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        @strongify(self);
        self.page ++;
        [self setLoad];
    }];
    self.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        @strongify(self);
        self.page = 0;
        [self setLoad];
    }];
    
}

-(void)setModel:(userUgcDetailModel *)model{
    _model = model;
    self.headView.model = model.userUgc;
    self.headView.modelLike = model;
    
    CGRect rect = self.headView.frame;
    [self layoutSubviews];
    [self layoutIfNeeded];
    NSLog(@"headView.height = %f", CGRectGetMaxY(self.headView.commentNum.frame));
    rect.size.height = CGRectGetMaxY(self.headView.commentNum.frame);
    self.headView.frame = rect;
    self.tableHeaderView = self.headView;

}

-(DetailFriedHeadView *)headView{
    if (!_headView) {
        _headView = [[DetailFriedHeadView alloc]initWithFrame:CGRectMake(0, 0, kScreenW, 800)];
        _headView.backgroundColor = [UIColor whiteColor];
    }
    return _headView;
}


#pragma MARK - 数据源
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (self.arrMComment.count == 0 ||self.arrMComment == nil) {
        return 1;
    }
    return self.arrMComment.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.arrMComment.count == 0 ||self.arrMComment == nil) {
        return [self getUgcDetailCummentNoMoreDataCell:indexPath];
    }
    /* TODO: ================= 判断 cell 样式 =================*/
    UgcCommentListModelSub *model = self.arrMComment[indexPath.row];
    NSLog(@"%@",model.isMaster);
    
    
    if ([Main_Token_Model_MANAGER.isToken isEqualToString:@"1"]){
        if ([model.isMaster isEqualToString:@"0"]) {
            return [self getUgcDetailCummentHeadCell_TokenCell:indexPath];
        }else{
            return [self getUgcDetailCummentCell_TokenCell:indexPath];
//            return [self getUgcDetailCummentCell:indexPath];

        }
    }else{
        if ([model.isMaster isEqualToString:@"0"]) {
            return [self getUgcDetailCummentHeadCell:indexPath];
        }else{
            return [self getUgcDetailCummentCell:indexPath];
        }
    }
    

}


-(UITableViewCell *)getUgcDetailCummentNoMoreDataCell:(NSIndexPath *)indexPath{

    static NSString *sectionCell = @"UgcDetailCummentNoMoreDataCell";
    UgcDetailCummentNoMoreDataCell *cell = [self dequeueReusableCellWithIdentifier:sectionCell];
    if (cell == nil) {
        cell = [[UgcDetailCummentNoMoreDataCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:sectionCell];
    }
    
    cell.selectionStyle = UITableViewCellSeparatorStyleNone;
    cell.backgroundColor = [UIColor colorWithHex:@"f5f5f5"];
    
    return cell;
}


/**
 #import "UgcDetailCummentCell_TokenCell.h"
 #import "UgcDetailCummentHeadCell_TokenCell.h"
 */


-(UITableViewCell *)getUgcDetailCummentHeadCell_TokenCell:(NSIndexPath *)indexPath{
    UgcCommentListModelSub *model = self.arrMComment[indexPath.row];

    static NSString *sectionCell = @"UgcDetailCummentHeadCell_TokenCell";
    UgcDetailCummentHeadCell_TokenCell *cell = [self dequeueReusableCellWithIdentifier:sectionCell];
    if (cell == nil) {
        cell = [[UgcDetailCummentHeadCell_TokenCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:sectionCell];
    }
    cell.indexPath = indexPath;

    cell.selectionStyle = UITableViewCellSeparatorStyleNone;
    cell.modelComment = model;
    cell.viewLine.hidden = indexPath.row==0?YES:NO;
    //    cell.backgroundColor = [UIColor colorWithHex:@"f5f5f5"];
    
    return cell;
}


-(UITableViewCell *)getUgcDetailCummentCell_TokenCell:(NSIndexPath *)indexPath{
    UgcCommentListModelSub *model = self.arrMComment[indexPath.row];
    static NSString *sectionCell = @"UgcDetailCummentCell_TokenCell";
    UgcDetailCummentCell_TokenCell *cell = [self dequeueReusableCellWithIdentifier:sectionCell];
    if (cell == nil) {
        cell = [[UgcDetailCummentCell_TokenCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:sectionCell];
    }
    cell.selectionStyle = UITableViewCellSeparatorStyleNone;
//    cell.backgroundColor = [UIColor colorWithHex:@"f5f5f5"];
    cell.modelComment = model;
    return cell;
}

-(UITableViewCell *)getUgcDetailCummentHeadCell:(NSIndexPath *)indexPath{
    UgcCommentListModelSub *model = self.arrMComment[indexPath.row];

    static NSString *sectionCell = @"UgcDetailCummentHeadCell";
    UgcDetailCummentHeadCell *cell = [self dequeueReusableCellWithIdentifier:sectionCell];
    if (cell == nil) {
        cell = [[UgcDetailCummentHeadCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:sectionCell];
    }
    
    cell.selectionStyle = UITableViewCellSeparatorStyleNone;
    cell.modelComment = model;
    cell.viewLine.hidden = indexPath.row==0?YES:NO;
    
    return cell;
}


-(UITableViewCell *)getUgcDetailCummentCell:(NSIndexPath *)indexPath{
    UgcCommentListModelSub *model = self.arrMComment[indexPath.row];

    static NSString *sectionCell = @"UgcDetailCummentCell";
    UgcDetailCummentCell *cell = [self dequeueReusableCellWithIdentifier:sectionCell];
    if (cell == nil) {
        cell = [[UgcDetailCummentCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:sectionCell];
    }
    cell.selectionStyle = UITableViewCellSeparatorStyleNone;
    
    cell.modelComment = model;
    return cell;
}





- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    UgcCommentListModelSub *model = self.arrMComment[indexPath.row];

    QMUIAlertAction *action1 = [QMUIAlertAction actionWithTitle:@"取消" style:QMUIAlertActionStyleCancel handler:^(__kindof QMUIAlertController *aAlertController, QMUIAlertAction *action) {
    }];
    
    QMUIAlertAction *action4 = [QMUIAlertAction actionWithTitle:@"回复" style:QMUIAlertActionStyleDefault handler:^(__kindof QMUIAlertController *aAlertController, QMUIAlertAction *action) {
//        [self btnClick:1];
        [self sendComment:indexPath];
    }];
    
    NSString *name = @"";
    
    if ([kUSER_INFO_MANAGER.userId isEqualToString:model.userId]) {
        name = @"删除";
    }else{
        name = @"举报";
    }
    

    
    QMUIAlertAction *ac2 = [QMUIAlertAction actionWithTitle:name style:QMUIAlertActionStyleDefault handler:^(__kindof QMUIAlertController *aAlertController, QMUIAlertAction *action) {
        
        if ([kUSER_INFO_MANAGER.userId isEqualToString:model.userId]) {
            [self removeComment:model index:indexPath];
        }else{
            
            ReportView *rep = [[ReportView alloc]initWithFrame:CGRectMake(0,0, kScreenW, kScreenH)];
            
            if (model.commentParentId.length != 0) {
                rep.typeId = model.commentMasterId;
            }else{
                rep.typeId = model.commentParentId;
            }            
            rep.state = ReportViewStateComent;
            [rep show];
        }
        
    }];
    
    QMUIAlertController *alertController = [QMUIAlertController alertControllerWithTitle:@"" message:@"" preferredStyle:QMUIAlertControllerStyleActionSheet];
    
    [alertController addAction:action4];
    
    [alertController addAction:action1];
    if (![kUSER_INFO_MANAGER.userId isEqualToString:model.userId]) {
        QMUIAlertAction *action3 = [QMUIAlertAction actionWithTitle:@"屏蔽用户" style:QMUIAlertActionStyleDefault handler:^(__kindof QMUIAlertController *aAlertController, QMUIAlertAction *action) {
            
            [[AccountService loadUserRepelAdd:model.userId reponseObjctClass:nil]subscribeNext:^(ResponseData* x) {
                if (x.success) {
                    [Tools showTips:@"已屏蔽"];
                }else{
                    [Tools showTips:x.errorInfo];
                }
            }];
        }];
        [alertController addAction:action3];
    }

    [alertController addAction:ac2];
    
    [alertController showWithAnimated:YES];

}

-(void)removeComment:(UgcCommentListModelSub*)model index:(NSIndexPath*)indexPath{
    @weakify(self);
    [[serviceDefualt loadDelUserCommentCommentId:model.commentId reponseObjctClass:nil]subscribeNext:^(ResponseData * x) {
        @strongify(self);
        if (x.success) {
            //无法定位到主评论的位置还需要获取主评论位置
            
 
            
            UgcCommentListModelSub *model = self.arrMComment [indexPath.row];
            NSMutableArray *arrIndexPath = [[NSMutableArray alloc]init];
            //删除子评论为与主评论同步 导致数组越界
            if (model.sonCommentList.count!=0) {
                for (int i = 0; i< model.sonCommentList.count; i++) {
                    [self.arrMComment removeObjectAtIndex:indexPath.row+1];
                    NSIndexPath *indexPath1 = [NSIndexPath indexPathForRow:indexPath.row+1+i inSection:0];
                    [arrIndexPath addObject:indexPath1];
                }
            }else{
                if (![model.isMaster isEqualToString:@"0"]) {
                    for (int i = indexPath.row ;i>=0 ; i--) {
                        UgcCommentListModelSub *model = self.arrMComment [i];
                        if (model.sonCommentList.count!=0) {
                            [model.sonCommentList removeObjectAtIndex:indexPath.row-i-1];
                            break;
                        }
                    }
                }
               
            }
            
            
            [self.arrMComment removeObjectAtIndex:indexPath.row];

                if (self.arrMComment.count == 0) {
                    [self reloadData];
                    self.model.userUgc.commentCount = @"0";
                    [self setModel:self.model];
                }else{
                    if (arrIndexPath.count ==0 ) {
                        [self beginUpdates];
                        [self deleteRowsAtIndexPaths:@[indexPath]  withRowAnimation:UITableViewRowAnimationTop];
                        [self endUpdates];
                        
                        self.model.userUgc.commentCount = [NSString stringWithFormat:@"%ld",[self.model.userUgc.commentCount integerValue]-1];
                        [self setModel:self.model];
                    }else{
                        [self beginUpdates];
                        [arrIndexPath addObject:indexPath];
                        [self deleteRowsAtIndexPaths:arrIndexPath  withRowAnimation:UITableViewRowAnimationFade];
                        [self endUpdates];
                        
                        self.model.userUgc.commentCount = [NSString stringWithFormat:@"%ld",[self.model.userUgc.commentCount integerValue]-arrIndexPath.count];
                        [self setModel:self.model];
                    }
                 
                }
 
            [Tools showTips:@"删除成功"];
        }else{
            [Tools showTips:x.errorInfo];
        }
    }];
}


-(void)sendComment:(NSIndexPath *)indexPath{
    UgcCommentListModelSub *model = self.arrMComment[indexPath.row];
    /** 点击回复评论 */
    if ([model.isMaster isEqualToString:@"0"]) {
        /** 自己回复自己 */
        if (self.keyboard) {
            self.keyboard(model.nickName,self.ugcId, model.userId, @"1", model.commentId, model.commentId,1,indexPath.row);
        }
    }else{
        if (self.keyboard) {
            self.keyboard(model.nickName,self.ugcId, model.userId, @"1", model.commentId, model.commentMasterId,2,indexPath.row);
        }
    }
}

-(NSMutableArray *)arrMComment{
    if (!_arrMComment) {
        _arrMComment = [[NSMutableArray alloc]init];
    }
    return _arrMComment;
}

@end
